<?php

namespace app\admin\controller\business;

// 引入基类控制器
use app\common\controller\Backend;

// 客户来源
class Source extends Backend
{
    public function __construct()
    {
        parent::__construct();

        $this->model = model('Business.Source');
    }

    public function index()
    {
        if ($this->request->isAjax()) {
            // 过滤请求参数中的html标签和取消两边你空白
            $this->request->filter(['strip_tags', 'trim']);
            // 获取查询参数
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->count();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = [
                'rows' => $list,
                'total' => $total
            ];

            return json($result);
        }

        return $this->view->fetch();
    }

    public function add()
    {
        
        if ($this->request->isPost()) {
            $params = $this->request->param('row/a');

            $data = [
                'name' => $params['name'],
            ];

            $result = $this->model->validate('common/Business/Source')->save($data);

            if ($result) {
                $this->success('添加客户来源成功');
                exit;
            } else {
                $this->error($this->model->getError());
                exit;
            }
        }

        return $this->view->fetch();
    }

    public function edit($ids = null)
    {
        $row = $this->model->where('id', $ids)->find();

        if(!$row){
            $this->error(__('No Results were found'));
            exit;
        }

        if ($this->request->isPost()) {
            $params = $this->request->param('row/a');

            $data = [
                'id' => $ids,
                'name' => $params['name'],
            ];

            $result = $this->model->validate('common/Business/Source')->isUpdate(true)->save($data);

            if ($result) {
                $this->success('修改客户来源成功');
                exit;
            } else {
                $this->error($this->model->getError());
                exit;
            }
        }

        $this->view->assign('row', $row);

        return $this->view->fetch();
    }

    public function del($ids = null)
    {
        $row = $this->model->whereIn('id', $ids)->find();

        if(!$row){
            $this->error(__('No Results were found'));
            exit;
        }

        $result = $this->model->whereIn('id', $ids)->delete();

        if ($result) {
            $this->success('删除客户来源成功');
            exit;
        }

        $this->error('删除客户来源失败');
        exit;
    }
}
